package com.yutao.utils;

import com.yutao.domain.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @explain Redis订阅频道属性类
 */
@Component
public class RedisListenerBean {
	private static final Logger LOGGER = LoggerFactory.getLogger(RedisListenerBean.class);

	/**
	 * redis消息监听器容器 可以添加多个监听不同话题的redis监听器，只需要把消息监听器和相应的消息订阅处理器绑定，该消息监听器
	 * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
	 *
		**/
	private String room;
	@Bean
	public String setRoom(String room){
		this.room = room;
		return room;
	}
	/**
	 * 消息适配器
	 * <p>
	 * 绑定消息监听者和接收监听的方法,必须要注入这个监听器，不然会报错
	 *
	 * @return MessageListenerAdapter
	 */
	@Bean
	public MessageListenerAdapter listenerAdapter(List<Player> list) {
		return new MessageListenerAdapter(list);
	}

	/**
	 * 定义消息监听者容器
	 *
	 * @param connectionFactory 连接工厂
	 * @param listenerAdapter   消息处理器
	 * @return RedisMessageListenerContainer
	 */
	@Bean
	public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
												   MessageListenerAdapter listenerAdapter) {
		RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
		listenerContainer.setConnectionFactory(connectionFactory);
		listenerContainer.addMessageListener(listenerAdapter, new PatternTopic(room));
		return listenerContainer;
	}
}